﻿#region Creditos

/* Autor: Edilberto Sánchez Forero	*/
/* Email: esanchezfo@gmail.com		*/
/* Licencia: LGPL, Software Libre	*/
/* País: Colombia, Bogotá			*/

#endregion

#region Librerias

using System;
using System.Net.Mail;
using System.Threading;

#endregion


namespace ESF.General
{
	public static class EmailSender
	{
		// TODO: Implementar un Message Queue para garantizar el envio de mensajes en condiciones fallidas
	
		#region Envio
	
		public static bool Send (string pstrSubject, string pstrBody, bool pblnIsHtml = false, bool pCopyToLog = false, bool pIgnoreBadEmailTo = true, params string [] pstrTo)
		{
			MailMessage msg;

			
			msg = new MailMessage ();
						
			if (DataHelper.IsEmpty (pstrTo))
			{
				return false;
			}


			foreach (string to in pstrTo)
			{
				if (!TextHelper.IsEmail(to))
				{
					if (pIgnoreBadEmailTo)
					{
						continue;
					}

					throw new FormatException(string.Format("{0} is not a valid email", to));
				}
				
				msg.To.Add (to);				
			}
						
			msg.Subject = pstrSubject;
			msg.Body = pstrBody;
			msg.IsBodyHtml = pblnIsHtml;

			return Send (msg);
		}


		public static bool Send (MailMessage pMessage)
		{
			return Send (pMessage, false, false);
		}


		public static bool Send (MailMessage pMessage, bool pCopyToLog, bool pThrowException)
		{
			SmtpClient objSmtpClient;
			
			
			objSmtpClient = new SmtpClient ();
			
			try
			{
				if (objSmtpClient.Host.ToLower ().EndsWith (".gmail.com"))
				{
					objSmtpClient.EnableSsl = true;
				}
			
				objSmtpClient.Send (pMessage); 

				if (pCopyToLog)
				{
					Log.WriteStartHistory (
						string.Format ("The email with subject: '{0}' to email {1} using host {2} (usessl={3} port={4}) was send", 
						pMessage.Subject, pMessage.To [0], objSmtpClient.Host, objSmtpClient.EnableSsl, objSmtpClient.Port));
				}

				return true;
			}
			catch (Exception excEx)
			{
				if (pThrowException)
				{
					throw excEx;
				}
				else
				{
					Log.Error (
						string.Format ("The email with subject: '{0}' to email {1} using host {2} (usessl={3} port={4}) was not send", 
						pMessage.Subject, pMessage.To [0], objSmtpClient.Host, objSmtpClient.EnableSsl, objSmtpClient.Port), excEx);

					return false;
				}
			}
		}
	
		#endregion
	}
}
